package com.ikun.yummy.activitys.post;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Application;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.databinding.BindingAdapter;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.MutableLiveData;

import com.ikun.yummy.App;
import com.ikun.yummy.R;
import com.ikun.yummy.bean.CookInfo;
import com.ikun.yummy.bean.UserInfo;
import com.ikun.yummy.databinding.ActivityPostBinding;
import com.ikun.yummy.manager.CookOpManager;
import com.ikun.yummy.manager.UserOpManager;
import com.ikun.yummy.utils.CommonUtils;
import com.ikun.yummy.utils.ReadImageUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.HashMap;
import java.util.Objects;

public class PostVM extends AndroidViewModel {
    @SuppressLint("StaticFieldLeak")
    private static PostActivity postActivity;
    //存删除的和增加的步骤
    public static MutableLiveData<HashMap<String,Object>> step;
    //总数居
    public static JSONObject DATA=new JSONObject();
    //要存入数据库的数据监听变量
    public static MutableLiveData<String> imgDir=new MutableLiveData<>();
    public static MutableLiveData<String> cookName=new MutableLiveData<>();
    public static MutableLiveData<String> story=new MutableLiveData<>();
    public static MutableLiveData<HashMap<String,String>> ingredients=new MutableLiveData<>();
    public static MutableLiveData<String> time=new MutableLiveData<>();
    public static MutableLiveData<String> difficulty=new MutableLiveData<>();
    public static MutableLiveData<String> taste=new MutableLiveData<>();
    public static MutableLiveData<String> classification=new MutableLiveData<>();
    @SuppressLint("StaticFieldLeak")
    public static LinearLayout temStepLinearLayout,temIngLinearLayout;
    public PostVM(@NonNull Application application) {
        super(application);
        imgDir.setValue("");
        cookName.setValue("");
        story.setValue("");
        time.setValue("");
        difficulty.setValue("");
        taste.setValue("");
        classification.setValue("");
        step=new MutableLiveData<>();
        step.setValue(null);
        ingredients.setValue(null);
    }
    public void setBinding(ActivityPostBinding binding, PostActivity postActivity) {
        PostVM.postActivity =postActivity;
        resumeDraft();
    }
    //恢复草稿
    private void resumeDraft() {
        boolean hasResume = false;
        String draft=App.sp.getString("draft","null");
        if (!draft.equals("null")){
            try {
                DATA=new JSONObject(draft);
                String user=App.sp.getString("username","null");
                if (!user.equals("null")){
                    UserOpManager userOpManager=new UserOpManager(postActivity);
                    UserInfo userInfo = userOpManager.queryUser(user);
                    if (userInfo.loginstate.equals("1")){
                        if (userInfo.username.equals(DATA.getString("username"))){
                            hasResume=true;
                            imgDir.setValue(DATA.getString("imgDir"));
                            cookName.setValue(DATA.getString("cookName"));
                            story.setValue(DATA.getString("story"));
                            time.setValue(DATA.getString("time"));
                            difficulty.setValue(DATA.getString("difficulty"));
                            taste.setValue(DATA.getString("taste"));
                            classification.setValue(DATA.getString("classification"));
                            //食材
                            JSONArray ing = DATA.getJSONArray("ingredients");
                            HashMap<String,String> hash=new HashMap<>();
                            hash.put("onlyOne","false");
                            hash.put("text",ing.toString());
                            ingredients.postValue(hash);
                            //步骤
                            HashMap<String,Object> hash1=new HashMap<>();
                            JSONObject steps = DATA.getJSONObject("step");
                            hash1.put("onlyOne",false);
                            hash1.put("jobj",steps);
                            step.postValue(hash1);
                        }
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        //没用了
        if (!hasResume){ //没恢复草稿就自增，防止重复恢复
            HashMap<String,String> hash=new HashMap<>();
            hash.put("onlyOne","true");
            hash.put("text","");
            ingredients.setValue(hash);
        }
    }
    @RequiresApi(api = Build.VERSION_CODES.O)
    public void publish() {
        //手动添加
        handinData();
        //要把图片命名后都放进内部储存的一个专门的图片文件夹里，代表他们路径信息以写入数据库，用以区分post的临时文件数据
        try {
            String path = DATA.getString("imgDir");
            String timestamp=String.valueOf(System.currentTimeMillis());
            File file=new File(CommonUtils.getPath(postActivity)+"/sqlPic/cover_"+timestamp+".jpg");
            if (!Objects.requireNonNull(file.getParentFile()).exists()){
                file.getParentFile().mkdir();
            }
            Files.copy(new File(path).toPath(),file.toPath());
            DATA.put("imgDir",file.getAbsolutePath());
            path = DATA.getString("userimage");
            timestamp=String.valueOf(System.currentTimeMillis());
            File file1=new File(CommonUtils.getPath(postActivity)+"/sqlPic/head_"+timestamp+".jpg");
            Files.copy(new File(path).toPath(),file1.toPath());
            DATA.put("userimage",file1.getAbsolutePath());
            //更改对象文件路径
            JSONObject stepObj;
            if (DATA.isNull("step")){
                stepObj = new JSONObject();
            }else{
                try {
                    stepObj=DATA.getJSONObject("step");
                } catch (JSONException e) {
                    stepObj = new JSONObject();
                }
            }
            for (int i = 0; i < stepObj.length(); i++) {
                JSONObject stepBean = stepObj.getJSONObject("step" + i);
                if (!stepBean.isNull("img")){
                    path=stepBean.getString("img");
                    timestamp=String.valueOf(System.currentTimeMillis());
                     file=new File(CommonUtils.getPath(postActivity)+"/sqlPic/"+timestamp+".jpg");
                     Files.copy(new File(path).toPath(),file.toPath());
                    stepBean.put("img",file.getAbsolutePath());
                }
                stepObj.put("step" + i,stepBean);
            }
            DATA.put("step",stepObj);
            try {
                CookOpManager cookOpManager=new CookOpManager(postActivity);


                DATA.getString("imgDir");
                if (!DATA.getString("imgDir").equals("") && !DATA.getString("cookName").equals("") && !DATA.getString("difficulty").equals("") && !DATA.getString("taste").equals("") && !DATA.getString("classification").equals("") && !DATA.getString("story").equals("")){
                    cookOpManager.insert(new CookInfo(
                            "",
                            DATA.getString("imgDir"),//图片路径处理
                            DATA.getString("cookName"),
                            DATA.getString("username"),
                            DATA.getJSONArray("ingredients").toString(),
                            DATA.getJSONObject("step").toString(),//图片路径处理
                            DATA.getString("time"),
                            DATA.getString("difficulty"),
                            DATA.getString("taste"),
                            DATA.getString("classification"),
                            DATA.getString("story"),
                            DATA.getString("userimage"),//头像
                            false,null ));

//                清理草稿,可以不用删除本地内部储存文件，下次发表自动替换
                    SharedPreferences.Editor edit = App.sp.edit();
                    edit.putString("draft",null);
                    edit.apply();
                    Toast.makeText(postActivity,"发布成功",Toast.LENGTH_SHORT).show();
                    DATA=null;
                    postActivity.finish();
                }else{
                    Toast.makeText(postActivity, "请填写完整再发布！", Toast.LENGTH_SHORT).show();
                }
            } catch (JSONException e) {
                Toast.makeText(postActivity,"发布失败",Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            Toast.makeText(postActivity,"发布失败",Toast.LENGTH_SHORT).show();
        }
    }
    //保存草稿
    public void saveAsDraft() {
        handinData();
        @SuppressLint("CommitPrefEdits") SharedPreferences.Editor edit = App.sp.edit();
        edit.putString("draft",DATA.toString());
        edit.apply();
        DATA=null;
        postActivity.finish();
    }
    private void handinData() {
        //遍历控件，添加步骤
        if (temStepLinearLayout!=null){
            //获取步骤对象
            JSONObject stepObj;
            if (DATA==null){
                DATA=new JSONObject();
            }
            if (DATA.isNull("step")){
                stepObj = new JSONObject();
            }else{
                try {
                    stepObj=DATA.getJSONObject("step");
                } catch (JSONException e) {
                    stepObj = new JSONObject();
                }
            }
            for (int i = 0; i < temStepLinearLayout.getChildCount(); i++){
                final LinearLayout child = (LinearLayout) temStepLinearLayout.getChildAt(i);
                if ((int)child.getTag()!=1){
                    EditText editText= (EditText) child.getChildAt(child.getChildCount()-2);//获取到EditText的位置
                    JSONObject jsonObjectBean = null;
                    if (! stepObj.isNull("step"+i)){
                        try {
                            jsonObjectBean = stepObj.getJSONObject("step" + i);
                            jsonObjectBean.put("text",editText.getText().toString());
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }else{
                        try {
                            jsonObjectBean = new JSONObject();
                            jsonObjectBean.put("text",editText.getText().toString());
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    //该步骤加入
                    try {
                        stepObj.put("step"+i,jsonObjectBean);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
            try { DATA.put("step",stepObj); } catch (JSONException ignored) {}
        }
        //遍历控件,添加食材
        if (temIngLinearLayout!=null){
            JSONArray jsonArray=new JSONArray();
            for (int i = 0; i < temIngLinearLayout.getChildCount(); i++) {
                final LinearLayout child = (LinearLayout) temIngLinearLayout.getChildAt(i);
                EditText editText= (EditText) child.getChildAt(0);
                jsonArray.put(editText.getText().toString());
            }
            try { DATA.put("ingredients",jsonArray); } catch (JSONException ignored) { }
        }
        //添加其他数据信息
        try {
            DATA.put("imgDir",imgDir.getValue());
            DATA.put("cookName",cookName.getValue());
            DATA.put("story",story.getValue());
            DATA.put("time",time.getValue());
            DATA.put("difficulty",difficulty.getValue());
            DATA.put("taste",taste.getValue());
            DATA.put("classification",classification.getValue());
            //存入用户数据
            String user= App.sp.getString("username","null");
            if (!user.equals("null")){
                UserOpManager userOpManager=new UserOpManager(postActivity);
                UserInfo userInfo = userOpManager.queryUser(user);
                if (userInfo.loginstate.equals("1")){
                    DATA.put("username", userInfo.username);
                    DATA.put("userimage", userInfo.userimage);
                }else {
                    DATA.put("username","未知用户");
                    DATA.put("userimage","");
                }
            }else {
                DATA.put("username","未知用户");
                DATA.put("userimage","");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    public void back() {
        AlertDialog.Builder dialog=new AlertDialog.Builder(postActivity);
        dialog.setTitle("提示").setMessage("是否保存为草稿?").setPositiveButton("保存", (dialog1, which) -> {
            saveAsDraft();
        }).setNegativeButton("退出", (dialog12, which) -> {
            //删除上次的草稿
            @SuppressLint("CommitPrefEdits") SharedPreferences.Editor edit = App.sp.edit();
            edit.putString("draft",null);
            edit.apply();
            //删不删图片无所谓，因为新选择图片时也会删除
            DATA=null;
            postActivity.finish();
        }).setNeutralButton("取消",null).show();
    }
    //imgDir被setValue就会执行app:bindImg
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @BindingAdapter("bindImg")
    public static void bindImg(ImageView imageView, MutableLiveData<String>imgDir){
        if (!Objects.equals(imgDir.getValue(), "")){
            File file=new File(Objects.requireNonNull(imgDir.getValue()));
            if (file.exists()){
                imageView.setImageBitmap(BitmapFactory.decodeFile(imgDir.getValue()));
            }
        }
    }
    //点击选择图片
    public void chooseImg(View view){
        postActivity.startActivityForResult(new Intent("android.intent.action.GET_CONTENT").setType("image/*"), 200);
    }
    @BindingAdapter("bindExpendView")//绑定步骤扩展组件
    public static void bindExpendView(LinearLayout linearLayout,MutableLiveData<HashMap<String,Object>> step){
        temStepLinearLayout=linearLayout;
        if(step!=null && step.getValue()!=null){
            HashMap<String, Object> hash = step.getValue();
            boolean onlyOne= (boolean) hash.get("onlyOne");
            if (onlyOne){
                int layoutId = (int) hash.get("layout");
                LinearLayout view = null;
                if (layoutId==0){
                    view= (LinearLayout) View.inflate(postActivity, R.layout.item_post_step_pic_and_text, null);
                }
                if (layoutId==1){
                    view= (LinearLayout) View.inflate(postActivity, R.layout.item_post_step_pic, null);
                }
                if (layoutId==2){
                    view= (LinearLayout) View.inflate(postActivity, R.layout.item_post_step_text, null);
                }
                assert view != null;
                view.setTag(layoutId);
                //定义每一步骤删除事件
                Button bt=(Button) view.getChildAt(view.getChildCount()-1);
                bt.setOnClickListener(v->{
                    AlertDialog.Builder dialog=new AlertDialog.Builder(postActivity);
                    dialog.setTitle("提示").setMessage("确定删除该步骤?").setPositiveButton("确定", (dialog1, which) -> {
                        LinearLayout parent=(LinearLayout)v.getParent();
                        int index=((ViewGroup)parent.getParent()).indexOfChild(parent);
                        //删除图片数据
                        File des=new File(CommonUtils.getPath(postActivity)+"/step"+index+".jpg");
                        if (des.exists()){ des.delete(); }
                        //重排序:如果所删除的不是最后一项，则补进
                        if (index!=((ViewGroup) parent.getParent()).getChildCount()-1){
                            JSONObject stepObj;
                            if (DATA.isNull("step")){
                                stepObj = new JSONObject();
                            }else{
                                try {
                                    stepObj=DATA.getJSONObject("step");
                                } catch (JSONException e) {
                                    stepObj = new JSONObject();
                                }
                            }
                            //10条  01234 indx=5 6789
                            JSONObject newStepObj=new JSONObject();
                            for (int i = 0; i < index; i++) {
                                try {
                                    newStepObj.put("step"+i,stepObj.get("step"+i));
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                            for (int i = index; i < stepObj.length() - 1; i++) {
                                try {
                                    newStepObj.put("step"+i,stepObj.get("step"+i+1));
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }

                            try { DATA.put("step",newStepObj); } catch (JSONException e) { e.printStackTrace(); }
                        }
                        linearLayout.removeViewAt(index);

                    }).setNeutralButton("取消",null).show();
                });
                //定义有图步骤选图方法
                if (layoutId!=2){//0和1有图
                    ImageView img=(ImageView) view.getChildAt(1);
                    img.setOnClickListener(v -> {
                        //index是本步骤在父布局的位置，选图时携带
                        LinearLayout parent=(LinearLayout)v.getParent();
                        int index=((ViewGroup)parent.getParent()).indexOfChild(parent);
                        if (ContextCompat.checkSelfPermission(postActivity, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                            ActivityCompat.requestPermissions(postActivity, new String[]{ Manifest.permission. WRITE_EXTERNAL_STORAGE }, 1);
                        }else {
                            Intent intent = new Intent("android.intent.action.GET_CONTENT");
                            intent.setType("image/*");
                            postActivity.startActivityForResult(intent, index);
                        }
                    });
                }
                linearLayout.addView(view);
            }else {
                JSONObject obj= (JSONObject) hash.get("jobj");
                for (int i = 0; i < Objects.requireNonNull(obj).length(); i++) {
                    try {
                        JSONObject stepBean=obj.getJSONObject("step"+i);
                        //获取布局类型
                        int layoutId=0;
                        LinearLayout view = null;
                        if (!stepBean.isNull("img")&&!stepBean.isNull("text")){
                            view= (LinearLayout) View.inflate(postActivity, R.layout.item_post_step_pic_and_text, null);
                        }else{
                            if (!stepBean.isNull("img")){
                                layoutId = 1;
                                view= (LinearLayout) View.inflate(postActivity, R.layout.item_post_step_pic, null);
                            }else {
                                layoutId = 2;
                                view= (LinearLayout) View.inflate(postActivity, R.layout.item_post_step_text, null);
                            }
                        }
                        view.setTag(layoutId);
                        //定义每一步骤删除事件
                        Button bt=(Button) view.getChildAt(view.getChildCount()-1);
                        bt.setOnClickListener(v->{
                            AlertDialog.Builder dialog=new AlertDialog.Builder(postActivity);
                            dialog.setTitle("提示").setMessage("确定删除该步骤?").setPositiveButton("确定", (dialog1, which) -> {
                                LinearLayout parent=(LinearLayout)v.getParent();
                                int index=((ViewGroup)parent.getParent()).indexOfChild(parent);
                                //删除图片数据
                                File des=new File(CommonUtils.getPath(postActivity)+"/step"+index+".jpg");
                                if (des.exists()){ des.delete(); }
                                //重排序:如果所删除的不是最后一项，则补进
                                if (index!=((ViewGroup) parent.getParent()).getChildCount()-1){
                                    JSONObject stepObj;
                                    if (DATA.isNull("step")){
                                        stepObj = new JSONObject();
                                    }else{
                                        try {
                                            stepObj=DATA.getJSONObject("step");
                                        } catch (JSONException e) {
                                            stepObj = new JSONObject();
                                        }
                                    }
                                    //10条  01234 indx=5 6789
                                    JSONObject newStepObj=new JSONObject();
                                    for (int i1 = 0; i1 < index; i1++) {
                                        try {
                                            newStepObj.put("step"+i1,stepObj.get("step"+i1));
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                    for (int i2 = index; i2 < stepObj.length() - 1; i2++) {
                                        try {
                                            newStepObj.put("step"+i2,stepObj.get("step"+i2+1));
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }
                                    }

                                    try { DATA.put("step",newStepObj); } catch (JSONException e) { e.printStackTrace(); }
                                }
                                linearLayout.removeViewAt(index);
                            }).setNeutralButton("取消",null).show();
                        });
                        //定义有图步骤选图方法
                        if (layoutId!=2){//0和1有图
                            ImageView img=(ImageView) view.getChildAt(1);
                            img.setImageBitmap(BitmapFactory.decodeFile(stepBean.getString("img")));
                            img.setOnClickListener(v -> {
                                //index是本步骤在父布局的位置，选图时携带
                                LinearLayout parent=(LinearLayout)v.getParent();
                                int index=((ViewGroup)parent.getParent()).indexOfChild(parent);
                                if (ContextCompat.checkSelfPermission(postActivity, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                                    ActivityCompat.requestPermissions(postActivity, new String[]{ Manifest.permission. WRITE_EXTERNAL_STORAGE }, 1);
                                }else {
                                    Intent intent = new Intent("android.intent.action.GET_CONTENT");
                                    intent.setType("image/*");
                                    postActivity.startActivityForResult(intent, index);
                                }
                            });
                        }
                        if (layoutId!=1){//0和2有文字
                            EditText editText=(EditText) view.getChildAt(view.getChildCount()-2);
                            editText.setText(stepBean.getString("text"));
                        }
                        linearLayout.addView(view);
                    } catch (JSONException e) { e.printStackTrace();}
                }
            }
        }
    }
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @BindingAdapter("bindIngredients")//绑定添加食材的扩展组件
    public static void bindIngredients(LinearLayout linearLayout,MutableLiveData<HashMap<String,String>> ing){
        temIngLinearLayout=linearLayout;
        if (ing!=null&&ing.getValue()!=null){
            HashMap<String, String> hash = ing.getValue();
            if (Objects.equals(hash.get("onlyOne"), "true")){
                LinearLayout view= (LinearLayout) View.inflate(postActivity, R.layout.item_post_ingredient, null);
                EditText editText=(EditText)view.getChildAt(0);
                editText.setText(hash.get("text"));
                Button bt=(Button) view.getChildAt(1);
                bt.setOnClickListener(v -> {
                    if (linearLayout.getChildCount()==1){
                        hash.put("onlyOne","true");
                        hash.put("text","");
                        ingredients.setValue(hash);
                    }else{
                        LinearLayout me= (LinearLayout) v.getParent();
                        int index=((ViewGroup)me.getParent()).indexOfChild(me);
                        if (index==linearLayout.getChildCount()-1){
                            hash.put("onlyOne","true");
                            hash.put("text","");
                            ingredients.setValue(hash);
                        }else{
                            linearLayout.removeViewAt(index);
                            for (int i = 0; i < linearLayout.getChildCount(); i++) {
                                LinearLayout child= (LinearLayout) linearLayout.getChildAt(i);
                                Button b= (Button) child.getChildAt(1);
                                if (i==linearLayout.getChildCount()-1){
                                    b.setText("+");
                                }else{
                                    b.setText("-");
                                }
                            }
                        }
                    }
                });
                linearLayout.addView(view);
                for (int i = 0; i < linearLayout.getChildCount(); i++) {
                    LinearLayout child= (LinearLayout) linearLayout.getChildAt(i);
                    Button b= (Button) child.getChildAt(1);
                    if (i==linearLayout.getChildCount()-1){
                        b.setText("+");
                    }else{
                        b.setText("-");
                    }
                }
            }else{
                try {
                    JSONArray jsonArray=new JSONArray(hash.get("text"));
                    for (int i1 = 0; i1 < jsonArray.length(); i1++) {
                        LinearLayout view= (LinearLayout) View.inflate(postActivity, R.layout.item_post_ingredient, null);
                        EditText editText=(EditText)view.getChildAt(0);
                        editText.setText(jsonArray.getString(i1));
                        Button bt=(Button) view.getChildAt(1);
                        bt.setOnClickListener(v -> {
                            if (linearLayout.getChildCount()==1){
                                hash.put("onlyOne","true");
                                hash.put("text","");
                                ingredients.setValue(hash);
                            }else{
                                LinearLayout me= (LinearLayout) v.getParent();
                                int index=((ViewGroup)me.getParent()).indexOfChild(me);
                                if (index==linearLayout.getChildCount()-1){
                                    hash.put("onlyOne","true");
                                    hash.put("text","");
                                    ingredients.setValue(hash);
                                }else{
                                    linearLayout.removeViewAt(index);
                                    for (int i = 0; i < linearLayout.getChildCount(); i++) {
                                        LinearLayout child= (LinearLayout) linearLayout.getChildAt(i);
                                        Button b= (Button) child.getChildAt(1);
                                        if (i==linearLayout.getChildCount()-1){
                                            b.setText("+");
                                        }else{
                                            b.setText("-");
                                        }
                                    }
                                }
                            }
                        });
                        linearLayout.addView(view);
                        for (int i = 0; i < linearLayout.getChildCount(); i++) {
                            LinearLayout child= (LinearLayout) linearLayout.getChildAt(i);
                            Button b= (Button) child.getChildAt(1);
                            if (i==linearLayout.getChildCount()-1){
                                b.setText("+");
                            }else{
                                b.setText("-");
                            }
                        }
                    }
                } catch (JSONException ignored) { }
            }
        }
    }
    //添加步骤
    public void addStep(View view){
        AlertDialog.Builder dialog=new AlertDialog.Builder(postActivity);
        dialog.setTitle("请选择类型").setItems(new String[]{"图和文","仅图","仅文"}, (dialog1, which) -> {
            HashMap<String,Object> hashMap=new HashMap<>();
            hashMap.put("onlyOne",true);
            switch (which){
                case 0:
                    hashMap.put("layout",0);
                    step.setValue(hashMap);
                    break;
                case 1:
                    hashMap.put("layout",1);
                    step.setValue(hashMap);
                    break;
                case 2:
                    hashMap.put("layout",2);
                    step.setValue(hashMap);
                    break;
            }
        }).show();
    }
    //下面四个点击选择的
    public void timeClick(View view){
        AlertDialog.Builder builder = new AlertDialog.Builder(postActivity);
        final String[] t = {"15分以内","15分钟~30分钟","30分钟~1小时","1小时~一天","一天以上"};
        builder.setTitle("烹饪时间：");
        builder.setSingleChoiceItems(t, 0, (dialogInterface, i) -> {
            time.postValue(t[i]);
            dialogInterface.dismiss();
        }).show();
    }
    public void difficultyClick(View view){
        AlertDialog.Builder builder = new AlertDialog.Builder(postActivity);
        final String[] t = {"简单","普通","高级"};
        builder.setTitle("难度：");
        builder.setSingleChoiceItems(t, 0, (dialogInterface, i) -> {
            difficulty.postValue(t[i]);
            dialogInterface.dismiss();
        }).show();
    }
    public void tasteClick(View view){
        AlertDialog.Builder builder = new AlertDialog.Builder(postActivity);
        final String[] t = {"咸鲜","酸甜","鱼香","五香","酸","香辣","辣","酸辣","孜然","甜"};
        builder.setTitle("口味：");
        builder.setSingleChoiceItems(t, 0, (dialogInterface, i) -> {
            taste.postValue(t[i]);
            dialogInterface.dismiss();
        }).show();
    }
    public void classificationClick(View view){
        AlertDialog.Builder builder = new AlertDialog.Builder(postActivity);
        final String[] t ={"荤菜","素菜","汤粥","面点","主食","小吃","西餐","饮品","养生"};
        builder.setTitle("分类：");
        builder.setSingleChoiceItems(t, 0, (dialogInterface, i) -> {
            classification.postValue(t[i]);
            dialogInterface.dismiss();
        }).show();
    }
    //图片返回
    @RequiresApi(api = Build.VERSION_CODES.O)
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode==200){
            if (resultCode== Activity.RESULT_OK){
                ReadImageUtil readImageUtil = new ReadImageUtil();
                String path=(Build.VERSION.SDK_INT >= 19)?readImageUtil.handleImageOnKitKat(postActivity,data):readImageUtil.handleImageBeforeKitKat(postActivity,data);
                File des=new File(CommonUtils.getPath(postActivity)+"/cookImg.jpg");
                if (des.exists()){
                    des.delete();
                }
                try {
                    Files.copy(new File(path).toPath(),des.toPath());
                } catch (IOException e) {
                    e.printStackTrace();
                }
                imgDir.setValue(CommonUtils.getPath(postActivity)+"/cookImg.jpg");
                
            }
        }else{//步骤中的图选择回来
            ReadImageUtil readImageUtil = new ReadImageUtil();
            String path=(Build.VERSION.SDK_INT >= 19)?readImageUtil.handleImageOnKitKat(postActivity,data):readImageUtil.handleImageBeforeKitKat(postActivity,data);
            File des=new File(CommonUtils.getPath(postActivity)+"/step"+requestCode+".jpg");
            if (des.exists()){ des.delete(); }
            try { Files.copy(new File(path).toPath(),des.toPath()); } catch (IOException ignored) { }
            JSONObject stepObj;
            if (DATA!=null){
                if (DATA.isNull("step")){
                    stepObj = new JSONObject();
                }else{
                    try {
                        stepObj=DATA.getJSONObject("step");
                    } catch (JSONException e) {
                        stepObj = new JSONObject();
                    }
                }
            }else{
                DATA=new JSONObject();
                stepObj = new JSONObject();
            }
            try {
                JSONObject stepBean=new JSONObject();
                stepBean.put("img",des.getAbsolutePath());
                stepObj.put("step"+requestCode,stepBean);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            try {
                DATA.put("step",stepObj);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            if (temStepLinearLayout!=null){
                LinearLayout linearLayout= (LinearLayout) temStepLinearLayout.getChildAt(requestCode);
                ImageView img=(ImageView) linearLayout.getChildAt(1);
                img.setImageBitmap(BitmapFactory.decodeFile(des.getAbsolutePath()));
            }
        }
    }
}
